-- upgrade_bine
-- Created by chengb Jul/18/2015
-- 成就：升级魔藤技能

-- 内部函数声明
local whenUpgradeBine;

-- 注册魔藤升级的回调
EventMgr.register("achievements/upgrade_bine", event.BINE_LEVEL_UP, function(args)
    whenUpgradeBine(args);
end);

-- 注册魔藤升级的回调
whenUpgradeBine = function(args)
    local level = args.level;
    
    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    local layer = DungeonM.currentLayer();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("upgrade_bine");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == AchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        if not AchievementM.isBelongTo(id, dungeonId) then
            -- 不是该迷宫的成就
            return false;
        end
        
        local config = AchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            if type(ruleArg["level"]) == 'number' and 
               level < ruleArg["level"] then
                -- 等级未达标 
                return false;
            end
        end

        return true;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            AchievementM.tryComplete(id, 1);
        end
    end
end

return {
    -- 获取成就描述
    queryDesc = function(id)
        local config = AchievementM.query(id);

        local ruleArg = config["rule_arg"];
        local level   = ruleArg["level"];
        local desc    = config["desc"];

        desc = string.gsub(desc, "{0}", level);

        return desc;
    end,
};